<template>
  <div class="container">
    <div class="handle-button">
      <label><input type="checkbox" v-model="editable">启用拖放</label>
      <button type="button" @click="orderList">恢复默认</button>
    </div>
    <draggable class="list-group" tag="ul" v-model="componentlist" v-bind="dragOptions" :move="onMove"
      @start="isDragging = true" @end="isDragging = false">
      <transition-group type="transition" :name="'flip-list'">
        <li v-for="element in componentlist" :key="element.order">
          <component :is="element.name"></component>
        </li>
      </transition-group>
    </draggable>
    <hr>
    {{ componentlist }}
  </div>
</template>

<script>
import draggable from "vuedraggable";
import viewOne from "../components/one.vue"
import viewTwo from "../components/two.vue"
import viewThree from "../components/three.vue"

export default {
  name: "hello",
  components: {
    draggable,
    viewOne,
    viewTwo,
    viewThree
  },
  data() {
    return {
      editable: true,
      isDragging: false,
      delayedDragging: false,
      componentlist: [
        { "name": "viewOne", "order": 1, "fixed": "false" },
        { "name": "viewTwo", "order": 2, "fixed": false },
        { "name": "viewThree", "order": 3, "fixed": false }
      ]
    };
  },
  methods: {
    orderList() {
      this.componentlist = this.componentlist.sort((one, two) => {
        return one.order - two.order;
      });
    },
    onMove({ relatedContext, draggedContext }) {
      const relatedElement = relatedContext.element;
      const draggedElement = draggedContext.element;
      return (
        (!relatedElement || !relatedElement.fixed) && !draggedElement.fixed
      );
    }
  },
  computed: {
    dragOptions() {
      return {
        animation: 0,
        group: "description",
        disabled: !this.editable,
        ghostClass: "ghost"
      };
    },

  },
  watch: {
    isDragging(newValue) {
      if (newValue) {
        this.delayedDragging = true;
        return;
      }
      this.$nextTick(() => {
        this.delayedDragging = false;
      });
    }
  }
};
</script>

<style lang='scss' type='text/scss' scoped>
.handle-button {
  padding: 10px;

  button {
    margin-left: 20px;
  }
}

.flip-list-move {
  transition: transform 0.5s;
}

.no-move {
  transition: transform 0s;
}

.ghost {
  opacity: 0.5;
  background: #c8ebfb;
}

.list-group {
  min-height: 500px;
}

.list-group-item i {
  cursor: pointer;
}


.list-group {
  width: 100%;

  li {
    cursor: move;
  }

  span {
    display: flex;
    flex-wrap: wrap;
  }
}
</style>